package com.work.user.controller;

import com.github.pagehelper.Page;
import com.work.entity.PageResult;
import com.work.entity.Result;
import com.work.entity.StatusCode;
import com.work.user.pojo.User;
import com.work.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //查询所有用户
    @GetMapping("/findAll")
    public Result findAll() {
        try {
            List<User> userList = userService.findAll();
            return new Result(true, StatusCode.FIND_Ok, "查询成功", userList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.FIND_ERROR, "查询失败");
        }
    }

    //根据id查询用户角色
    @GetMapping("/findById")
    public Result findById(@RequestParam Integer id){
        try {
            User user = userService.findById(id);
            return new Result(true, StatusCode.FIND_Ok, "查询成功", user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.FIND_ERROR, "查询失败");
        }
    }

    //分页查询所有用户
    @GetMapping(value = "/search/{page}/{size}")
    public Result findPage(@RequestParam Map searchMap, @PathVariable("page") int page, @PathVariable("size") int size) {
        try {
            Page<User> pageList = userService.findPage(searchMap, page, size);
            PageResult pageResult = new PageResult(pageList.getTotal(), pageList.getResult());
            return new Result(true, StatusCode.FIND_Ok, "查询成功", pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.FIND_ERROR, "查询失败");
        }
    }

    //多条件搜索用户数据
    @GetMapping(value = "/search")
    public Result findList(@RequestParam Map searchMap) {
        try {
            List<User> list = userService.findList(searchMap);
            return new Result(true, StatusCode.FIND_Ok, "查询成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.FIND_ERROR, "查询失败");
        }
    }

    //新增用户
    @PostMapping("/add")
    public Result add(@RequestBody User user, @RequestParam("roleIds") Integer[] roleIds) {
        try {
            userService.add(user, roleIds);
            return new Result(true, StatusCode.ADD_OK, "添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, StatusCode.ADD_ERROR, "添加失败");
        }
    }

    //修改用户
    @PutMapping("/update")
    public Result update(@RequestBody User user, @RequestParam("roleIds") Integer[] roleIds) {
        try {
            userService.update(user, roleIds);
            return new Result(true, StatusCode.UPDATE_Ok, "修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, StatusCode.UPDATE_ERROR, "修改失败");
        }
    }

    //重置密码
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String,String> map,Integer id){
        try {
            User user = userService.findById(id);
//            数据密码
            String password = user.getPassword();
//            获取盐
//            String s = BCrypt.gensalt();
//            对用户原密码进行加密
//            String old_hashpw = BCrypt.hashpw(old_password,s);
//            用户登录原密码明文
            String old_password = map.get("old_password");
//            使用原密码的明文比较数据库密文
            if (BCrypt.checkpw(old_password,password)){
                String new_password = map.get("new_password");
//                对新密码加密
                String new_hashpw = BCrypt.hashpw(new_password, BCrypt.gensalt());
                user.setPassword(new_hashpw);
                userService.updatePassword(user);
            }else {
                throw new Exception("原密码错误，修改失败");
            }
            return new Result(true, StatusCode.UPDATE_Ok, "重置密码成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, StatusCode.UPDATE_ERROR, "重置密码失败");
        }
    }

    //重置状态
    @PreAuthorize("hasAnyRole('admin')")
    @PutMapping("/updateStatus")
    public Result updateStatus(@RequestParam Integer id){
        try {
            User user = userService.findById(id);
            String status = user.getStatus();
            if (status.equals("1")){
                user.setStatus("0");
            }else if (status.equals("0")){
                user.setStatus("1");
            }
            userService.updateStatus(user);
            return new Result(true, StatusCode.UPDATE_Ok, "修改用户状态成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, StatusCode.UPDATE_ERROR, "修改用户状态失败");
        }
    }

    //删除用户
    @PreAuthorize("hasAnyRole('admin')")
    @DeleteMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        try {
            //超级管理员id=1，不允许删除
            if (id == 1) {
                return new Result(false, StatusCode.DELETE_ERROR, "超级用户不允许删除");
            }
//            //根据id查询用户
//            User user = userService.findById(id);
//            //获取用户状态
//            String status = user.getStatus();
//            //用户状态为1的话先停用该账号
//            if (status.equals("1")){
//                userService.updateStatus(id);
//                return new Result(true, StatusCode.DELETE_OK, "停用该用户账户成功");
//            }
            //不为1，状态为停用，直接删除
            userService.delete(id);
            return new Result(true, StatusCode.DELETE_OK, "删除成功");
        }catch (Exception e){
            return new Result(false,StatusCode.DELETE_ERROR,"删除失败");
        }
    }


    /*public static void main(String[] args) {
        String hashpw = BCrypt.hashpw("147258", BCrypt.gensalt());
        System.out.println(hashpw);
        System.out.println(BCrypt.checkpw("147258", hashpw));
    }*/

}
